local liwei = fk.CreateSkill{
  name = "investiture__liwei",
}

Fk:loadTranslationTable{
  ["investiture__liwei"] = "立危",
  [":investiture__liwei"] = "当你受到伤害后，本回合未受到过伤害的角色可对你使用【桃】或【梨】并摸两张牌；若你于一轮内未受到伤害，你于下一轮内可对其他角色发动“立危”。",

  ["#investiture__liwei-use"] = "立危：你可以对 %src 使用【桃】或【梨】并摸两张牌",

  ["@@investiture__liwei"] = "立危",

  ["$investiture__liwei1"] = "父侯羑里卦象凶，自有长子上祭坛！",
  ["$investiture__liwei2"] = "三牲太牢宴朝歌，何妨添我血肉羹",
}

---@param player ServerPlayer
---@param round boolean?
---@return boolean
local function suffered(player, round)
  local events = player.room.logic.all_game_events
  for i = #events, 1, -1 do
    if events[i].event == GameEvent.Damage then
      local d = events[i].data ---@type DamageData
      if d.damage > 0 and d.to == player then
        return true
      end
    elseif events[i].event == GameEvent.Turn and not round then
      return false
    elseif events[i].event == GameEvent.Round then
      return false
    end
  end
  return false
end

liwei:addEffect(fk.Damaged, {
  anim_type = "support",
  can_trigger = function (self, event, target, player, data)
    if target:hasSkill(liwei.name) then
      return player ~= target and not player.dead and not suffered(player)
    else
      return player:hasSkill(liwei.name) and player:getMark("@@investiture__liwei") == 1
    end
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local able_cards = table.filter(player:getCardIds("h"), function (id)
      return table.contains({"peach", "pear"}, Fk:getCardById(id).trueName)
      and not player:isProhibited(target, Fk:getCardById(id))
    end)

    local card = room:askToCards(player, {
      min_num = 1,
      max_num = 1,
      skill_name = liwei.name,
      cancelable = true,
      prompt = "#investiture__liwei-use:"..target.id,
      pattern = tostring(Exppattern{ id = able_cards })
    })

    if #card == 0 then return end
    event:setCostData(self, card[1])
    return true
  end,
  on_use = function (self, event, target, player, data)
    player.room:useCard{
      card = Fk:getCardById(event:getCostData(self)),
      from = player,
      tos = { target },
    }
    if player.dead then return end
    player:drawCards(2, liwei.name)
  end
})

liwei:addEffect(fk.RoundEnd, {
  can_refresh = function (self, event, target, player, data)
    return player:hasSkill(liwei.name)
  end,
  on_refresh = function (self, event, target, player, data)
    player.room:setPlayerMark(player, "@@investiture__liwei", suffered(player, true) and 0 or 1)
  end
})

return liwei